package com.ruoyi.auth.service;


import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Joiner;
import com.ruoyi.common.security.utils.AesCbcUtil;
import com.ruoyi.common.security.utils.HttpUtils;
import com.ruoyi.customer.api.domain.AuthPhone;
import com.ruoyi.customer.api.domain.WxLoginBody;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.customer.api.RemoteCustomerService;
import com.ruoyi.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class WxUserService {
    @Autowired
    RemoteCustomerService remoteCustomerService;
    @Autowired
    TokenService tokenService;

    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;
    private String wxApiHostUrl = "https://api.weixin.qq.com";
    private String ACCESS_TOKEN = "/cgi-bin/token";
    private String GET_USER_PHONE_NUMBER = "/wxa/business/getuserphonenumber?access_token=";
    /**
     * 微信登录
     *
     * @param sessionInfo 登录凭证 只能用一次
     * @return
     */
    public Map<String, Object> wxLogin(WxMaJscode2SessionResult sessionInfo, WxLoginBody wxLoginBody){
        //字符串转json
        String openId = sessionInfo.getOpenid();
        wxLoginBody.setOpenId(openId);
        //获取头像
        //        String avatarUrl = jsonObject.getString("avatarUrl");
        String avatarUrl = "";
        //还可以获取其他信息
        //根据openid判断数据库中是否有该用户
        //根据openid查询用户信息
        R<LoginUser> customerInfoByOpenId = remoteCustomerService.getCustomerInfoByOpenId(wxLoginBody , SecurityConstants.INNER);
        LoginUser loginUser = customerInfoByOpenId.getData();
        Map<String, Object> token = tokenService.createToken(loginUser);
        token.put("userInfo",loginUser);
        // 生成token
        return token;
    }



    public String authPhone(AuthPhone param) throws Exception {
        String code = param.getCode();
        String sessionKey = param.getSessionKey();
        String encryptedData = param.getEncryptedData();
        String iv = param.getIv();
        return authPhone(code, sessionKey, encryptedData, iv);
    }

    public String authPhone(String code, String sessionKey, String encryptedData, String iv) throws Exception {
        if (StringUtils.isNotBlank(code)) {
            // 使用微信API通过验证码获取用户手机号信息
            String url =wxApiHostUrl + GET_USER_PHONE_NUMBER + getAccessToken();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", code);
            String s = HttpUtils.sendPost(url, jsonObject.toJSONString());

            JSONObject obj = JSONObject.parseObject(s);
            return "0".equals(String.valueOf(obj.get("errcode"))) ? obj.toJSONString() : "";
        } else {
            // 使用AES解密获取的加密数据
            String str = AesCbcUtil.decrypt(encryptedData, sessionKey, iv, "UTF-8");
            // 判断解密结果是否有效
            return StringUtils.isNotBlank(str) ? JSONObject.parseObject(str).toJSONString() : "";
        }
    }

    public String getAccessToken() {
        Map<String, String> params = new HashMap(8);
        params.put("appid", appid);
        params.put("secret", secret);
        params.put("grant_type", "client_credential");

        String param = Joiner.on("&").withKeyValueSeparator("=").join(params);
        String s = HttpUtils.sendGet(wxApiHostUrl + ACCESS_TOKEN, param);
        return JSONObject.parseObject(s).getString("access_token");
    }
}
